using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace Tools.UI
{
    [AddComponentMenu("Tools/UI/OnPointerClickEvent")]
    public class OnPointerClickEvent : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        [SerializeField] private float clickExecuteTime = 0.25f;
        [SerializeField] private bool limitPosition;
        [SerializeField] private float limitDistance = 5f;
        [SerializeField] UnityEvent<PointerEventData> onPointerClickEvent;
        
        public UnityEvent<PointerEventData> PointerClickEvent => onPointerClickEvent;
        
        private bool _isPointerDown;
        private float _pointerDownTime;
        private Vector2 _downPosition;
        private int _pointerId;

        void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
        {
            if (!_isPointerDown)
            {
                _pointerDownTime = Time.time;
                _isPointerDown = true;
                _pointerId = eventData.pointerId;
                _downPosition = eventData.position;
            }
        }

        void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
        {
            if (_isPointerDown && _pointerId == eventData.pointerId)
            {
                _isPointerDown = false;
                if (Time.time - _pointerDownTime <= clickExecuteTime && (!limitPosition || (limitPosition && (eventData.position - _downPosition).sqrMagnitude <= limitDistance * limitDistance)))
                {
                    PointerClickEvent?.Invoke(eventData);
                }
            }
        }
    }
}
